package com.stu.common;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class SqlScheduling {
    @Value("stuoa.sqlPath")
    public String sqlPath;
    @Value("stuoa.mysqldump")
    public String mysqldump;
    /**
     * 每天凌晨执行备份 0 0 0 * * *
     * 秒 分 时 日 月 周 年（可选）
     */
    @Scheduled(cron = "0 0 0 * * *")
    public void sqldemo(){
        try {
            String comman = mysqldump;
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String fPath = sqlPath+simpleDateFormat.format(date)+".sql";
            Runtime rt = Runtime.getRuntime();
            Process child = rt.exec(comman);
            InputStream in = child.getInputStream();

            OutputStream out = new FileOutputStream(new File(fPath));

            byte[] bytes = new byte[1024];
            int len = -1;

            while ((len = in.read(bytes)) != -1) {
                out.write(bytes,0,len);
                out.flush();
            }
            out.close();
            in.close();
            System.out.println(simpleDateFormat.format(date)+"数据库stuoa备份成功");
        } catch (IOException e) {
            System.out.println(new Date()+"数据库stuoa备份失败");
            e.printStackTrace();
        }
    }

    public void sqldemo2(){
        try {
            String comman = "mysqldump -uroot -h localhost -P 3306 -p123456 student-system";

            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

            String fPath="d:/"+simpleDateFormat.format(date)+".sql";
            Runtime rt = Runtime.getRuntime();
            Process child = rt.exec(comman);
            InputStream in = child.getInputStream();

            OutputStream out = new FileOutputStream(new File(fPath));

            byte[] bytes = new byte[1024];
            int len = -1;

            while ((len = in.read(bytes)) != -1) {
                out.write(bytes,0,len);
                out.flush();
            }
            out.close();
            in.close();

            System.out.println(simpleDateFormat.format(date)+"数据库stuoa备份成功");
        } catch (IOException e) {
            System.out.println(new Date()+"数据库stuoa备份失败");
            e.printStackTrace();
        }
    }
}
